package com.spdzen.controller.admin;

import java.util.Date;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.spdzen.model.Video;
import com.spdzen.service.VideoService;
import com.spdzen.support.AdminLoginUtils;
import com.spdzen.support.LogUtils;
import com.spdzen.support.PageOffsetParam;
import com.spdzen.support.result.JsonResult;
import com.spdzen.vo.search.VideoAdminSearch;

@Controller
@RequestMapping("/admin/video")
public class VideoController {
	@Resource
	private VideoService videoService;

	@RequestMapping("/pageView.do")
	public String pageView() {
		return "/admin/video/videoPageView";
	}

	@RequestMapping("/queryPage.do")
	@ResponseBody
	public JsonResult queryPage(PageOffsetParam param, VideoAdminSearch search) {
		try {
			return JsonResult.success(videoService.selectPage(param, search));
		} catch (Exception e) {
			LogUtils.logError(e, param, search);
			return JsonResult.error();
		}
	}

	@RequestMapping("/addView.do")
	public String addView() {
		return "/admin/video/addVideoView";
	}

	@RequestMapping(path = { "/add.do" }, method = { RequestMethod.POST })
	@ResponseBody
	public JsonResult add(Video record) {
		record.setOperateTime(new Date());
		record.setOperateId(AdminLoginUtils.getUserId());
		
		try {
			videoService.insert(record);
			return JsonResult.success();
		} catch (Exception e) {
			LogUtils.logError(e, record);
			return JsonResult.error();
		}
	}

	@RequestMapping(path = { "/delete.do" })
	@ResponseBody
	public JsonResult delete(Long id) {
		try {
			videoService.deleteById(id);
			return JsonResult.success();
		} catch (Exception e) {
			LogUtils.logError(e, id);
			return JsonResult.error();
		}
	}

	@RequestMapping("/editView.do")
	public String updateView(Long id, HttpServletRequest request) {		
		request.setAttribute("id", id);
		return "/admin/video/updateVideoView";
	}

	@RequestMapping(path = { "/edit.do" }, method = { RequestMethod.POST })
	@ResponseBody
	public JsonResult update(Video record) {
		record.setOperateTime(new Date());
		record.setOperateId(AdminLoginUtils.getUserId());

		try {
			videoService.updateById(record);
			return JsonResult.success();
		} catch (Exception e) {
			LogUtils.logError(e, record);
			return JsonResult.error();
		}
	}

	@RequestMapping(path = { "/queryById.do" })
	@ResponseBody
	public JsonResult queryById(Long id) {
		if (id == null || id.longValue() < 1) {
			return JsonResult.errorParameter();
		}

		try {
			return JsonResult.success(videoService.selectAdminVOById(id));
		} catch (Exception e) {
			LogUtils.logError(e, id);
			return JsonResult.error();
		}
	}
}
